<?php
namespace WXAPI\Controller;
use Think\Page;
use Grafika\Color;
use Grafika\Grafika;
use Grafika\GrafikaHelper; 
use Grafika\Curl;
class PdaController extends BaseController {
    
    /**
     * 析构流函数
     */
    public function  __construct() {
        parent::__construct();
    }
	
    public function index(){
		echo I('callback')."(".json_encode([
			'code'=>'200',
			'infos'=>'连接成功！'
		]).")";
	}
	
    public function ruku(){
        $mobile_san = I('mobile_san');
        if($mobile_san){  //by sofwu 手机扫码入库
            $supplier_id = I('user_id');
            $pda_expired = M('pda_expired')->where(['user_id'=>$supplier_id])->find();
            if(!$pda_expired){
                exit(json_encode(array("status"=>0,'msg'=>'你还没有开启扫码入库模式')));
            }
            $expired = $pda_expired['expired'];
            $expired_time = $pda_expired['add_time'];
            $san_time = strtotime('+'.$expired.' minutes',strtotime($expired_time));
            $now = time();
            if($san_time < $now){
                exit(json_encode(array("status"=>1,'msg'=>'启扫码入库模式已经超时')));
            }
        }
		$order_id=I("order_id");
		$ruku_num=I("ruku_num");
		$pda_name_ruku=I("pda_name_ruku");
        $pda_pd2=M('pda')->where('pda_name="'.$pda_name_ruku.'"')->find();
        if(!$pda_pd2){
            exit(json_encode(array("status"=>0,'msg'=>'未认证设备')));
        }
		$pda_pd=M('pda')->where('pda_name="'.$pda_name_ruku.'"')->getField('fenbu_id'); //0广佛，1其他分部
		$pd=M('order')->where('order_id='.$order_id.' and order_status in (3,5)')->find();
		
		if($pd){
			echo I('callback')."(".json_encode([
				'code'=>'50',
				'infos'=>'此单已取消！'
			]).")";
			exit;
		}else{
			$pd_quyu=M('order')->where('order_id='.$order_id)->getField('ufenbu_id');
			if($pda_pd!=0 && $pda_pd!=$pd_quyu){
				echo I('callback')."(".json_encode([
					'code'=>'50',
					'infos'=>'此单不是该区域！'
				]).")";
				exit;
			}
		}
		
		//判断总部和分部字段
		$z=!empty($pda_pd) ? 'z' : '';

		$orders=M('order_jian a')
		->field('a.*,b.order_sn,b.consignee,b.jian_count,u.fast_flag,s.fast_flag as sfast_flag')
		->join('ty_order b on a.order_id=b.order_id')
		->join('ty_users u on u.user_id=b.user_id','left')
		->join('ty_store s on s.store_id=b.store_id','left')
		->where('a.order_id='.$order_id.' and a.'.$z.'status_r=0 and a.'.$z.'ruku_num='.$ruku_num)->find();

		$basic = tpCache('basic');
        $fast_ruku_time = $basic['fast_ruku_time'];
        $slow_ruku_time = $basic['slow_ruku_time'];
        $now = time();
        
        if($pda_name_ruku != 'tlc-to168'){
            if($fast_ruku_time && $slow_ruku_time) {
            $fast_time = explode('-', $fast_ruku_time);
            $slow_time = explode('-', $slow_ruku_time);
            $fast_start_time = strtotime($fast_time[0]);
            $fast_end_time = strtotime($fast_time[1]);
            $slow_start_time = strtotime($slow_time[0]);
            $slow_end_time = strtotime($slow_time[1]);
            $fast_flag = M('order a')
                ->join('ty_users b ON a.user_id = b.user_id', 'LEFT')
                ->where(['a.order_id' => $order_id])->getField('b.fast_flag');
            if ($fast_flag) {
                if (($now > $fast_start_time) && ($now < $fast_end_time)) {
                    echo I('callback')."(".json_encode([
    					'code'=>'50',
    					'infos'=>'快线订单禁止入库！'
    				]).")";
    				exit;
                    // exit(json_encode(array("status"=>0,'msg'=>'快线订单禁止入库!')));
                }
            } else {
                if (($now > $slow_start_time) || ($now < $slow_end_time)) {
                    echo I('callback')."(".json_encode([
    					'code'=>'50',
    					'infos'=>'订单禁止入库！'
    				]).")";
    				exit;
                    // exit(json_encode(array("status"=>0,'msg'=>'订单禁止入库!')));
                }
            }
        }
        }
        
		
        $ruku_time = strtotime(date("Y-m-d H:i:s"));
		if($orders){
			M('order_jian')
			->where('order_id='.$order_id.' and '.$z.'status_r=0 and '.$z.'ruku_num='.$ruku_num)
			->save([
				$z.'pda_name_ruku'=>$pda_name_ruku,
				$z.'ruku_time'=>$ruku_time,
				$z.'status_r'=>'1',
				'status_c'=> !empty($pda_pd) ? '1' : '0'
			]);

            M('order')->where('order_id='.$order_id)->setInc('ruku_count');
            M('users_price')->where('order_id='.$order_id)->setField(['status'=>1]);
            $ruku_order = M('order')->where('order_id='.$order_id)->find();
            if($ruku_order['jian_count'] == $ruku_order['ruku_count']){  //判断是否入库齐全才变已发货订单，司机待配送单那里才会有订单，不齐全的都会在异常订单
                M('order')->where('order_id='.$order_id)
                    ->save([
                        'order_status'=>1,
                        'shipping_status'=>1,
                        'ruku_last_time'=>$ruku_time
                    ]);
            }
			
			echo I('callback')."(".json_encode([
				'code'=>'200',
				'infos'=>$orders
			]).")";
		}else{
			echo I('callback')."(".json_encode([
				'code'=>'100',
				'infos'=>'此单已经入库！'
			]).")";
		}

    }
	
    public function chuku(){
		$order_id=I("order_id");
		$chuku_num=I("chuku_num");
		$pda_name_chuku=I("pda_name_chuku");

        $pda_pd2=M('pda')->where('pda_name="'.$pda_name_chuku.'"')->find();
        if(!$pda_pd2){
            exit(json_encode(array("status"=>0,'msg'=>'未认证设备')));
        }
		$pda_pd=M('pda')->where('pda_name="'.$pda_name_chuku.'"')->getField('fenbu_id'); //0广佛，1其他分部
		//判断总部和分部字段
		$z=!empty($pda_pd) ? 'z' : '';
		
		$orders=M('order_jian a')
		->field('a.*,b.order_sn,b.consignee,b.jian_count,b.user_id')
		->join('ty_order b on a.order_id=b.order_id')
		->where('a.order_id='.$order_id.' and a.'.$z.'status_c=0 and a.'.$z.'chuku_num='.$chuku_num)->find();

		if($orders){
			//判断是否出库
			$pd=M('order_jian')
			->where('order_id='.$order_id.' and '.$z.'status_r=0')->find();
			if($pd){
				echo I('callback')."(".json_encode([
					'code'=>'100',
					'infos'=>'此单未入库，禁止出库！'
				]).")";
				exit;
			}
			$pds=M('order')->where('order_id='.$order_id.' and order_status in (3,5)')->find();
			if($pds){
				echo I('callback')."(".json_encode([
					'code'=>'100',
					'infos'=>'此单已取消！'
				]).")";
				exit;
			}else{
			$pd_quyu=M('order')->where('order_id='.$order_id)->getField('ufenbu_id');
			if($pda_pd!=0 && $pda_pd!=$pd_quyu){
				echo I('callback')."(".json_encode([
					'code'=>'50',
					'infos'=>'此单不是该区域！'
				]).")";
				exit;
			}
			}


            $chuku_time = strtotime(date("Y-m-d H:i:s"));
			$orderInfo = M('order')->where('order_id='.$order_id)->find();
			if($orderInfo['ruku_count'] != $orderInfo['chuku_count']){
                M('order')->where('order_id='.$order_id)->setInc('chuku_count');
                
                M('order')->where('order_id='.$order_id)
                    ->save([
                        'chuku_last_time'=>$chuku_time,
                        'pda_qdzt'=>0,
                    ]);
            }
            
            $orderData = M('order')->where('order_id='.$order_id)->find();
            if($orderData['chuku_count'] > $orderData['ruku_count']){
                M('order')->where('order_id='.$order_id)->setField(['chuku_count'=>$orderData['ruku_count']]);
            }

			M('order_jian')
			->where('order_id='.$order_id.' and '.$z.'status_c=0 and '.$z.'chuku_num='.$chuku_num)
			->save([
				$z.'pda_name_chuku'=>$pda_name_chuku,
				$z.'chuku_time'=>$chuku_time,
				$z.'status_c'=>'1'
			]);
			
			//判断是否推送  
			$wxpd=M('order_jian')->where('order_id='.$order_id.' and '.$z.'status_c=1')->find();
			if(empty($wxpd)){
				$user=M('users')->where('user_id='.$orders['user_id'])->find();
				if($user['openid']){
					$wx_user = M('wx_user')->find();
					$chepai = M('pda')->where('pda_name="'.$pda_name_chuku.'"')->getField('user_name');
					$jssdk = new \Mobile\Logic\Jssdk($wx_user['appid'],$wx_user['appsecret']);
				// 	"appid":"wx7c609f6efbc804de",
					$wx_content='{
           "touser":"'.$user['openid'].'",
           "template_id":"K3Kh-RwRZH0sSpxDlo_363j9pIasxUNRkRlbduS-SIk",
           "url":"https://bwsshop.faxians.com/index.php/Mobile/Index/",  
           "miniprogram":{
             "appid":"wxb436b48cbe9616e0",
             "pagepath":"pages/member/index/index"
           },
           "data":{
                   "first": {
                       "value":"尊敬的  '.$orders['consignee'].'  您的订单已发货，请注意查收！",
                       "color":"#173177"
                   },
                   "keyword1":{
                       "value":"'.$orders['order_id'].'",
                       "color":"#173177"
                   },
				   "keyword2":{
				       "value":"'.$orders['order_sn'].'",
				       "color":"#173177"
				   },
                   "keyword3": {
                       "value":"'.$chepai.'",
                       "color":"#173177"
                   },
				   "keyword4": {
				       "value":"'.$orders['jian_count'].'件",
				       "color":"#173177"
				   },
				   "keyword5": {
				       "value":"'.date('Y-m-d H:i:s',time()).'",
				       "color":"#173177"
				   },
                   "remark":{
                       "value":"感谢您对我们的支持！",
                       "color":"#173177"
                   }
           }
       }';
			$jssdk->push_msg_mod($wx_content);
				}
			}
			
			echo I('callback')."(".json_encode([
				'code'=>'200',
				'infos'=>$orders
			]).")";
		}else{
			echo I('callback')."(".json_encode([
				'code'=>'100',
				'infos'=>'此单已经出库！'
			]).")";
		}
    }
}